package com.itheima.Service.Impl;

import com.itheima.Mapper.OrderDao;
import com.itheima.Service.ValidateCodeService;
import com.itheima.pojo.Member;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void send4Login(String telephone) {


        //查询是否注册会员
        Member member= orderDao.selectByPhoneNumber(telephone);
        if(member==null){
            member=new Member();
            member.setPhoneNumber(telephone);
            orderDao.addMember(member);
        }

        //生成验证码
        redisTemplate.opsForValue().set(telephone, RandomStringUtils.randomNumeric(6));
        redisTemplate.expire("telephone_"+telephone, 5,TimeUnit.MINUTES);
    }

    @Override
    public void login(Map<String, String> loginMessage) {


        if (redisTemplate.opsForValue().get(loginMessage.get("telephone")) == null) {
            throw new RuntimeException("验证码已过期");
        } else if (!redisTemplate.opsForValue().get(loginMessage.get("telephone")).equals(loginMessage.get("validateCode"))) {
            throw new RuntimeException("验证码错误");
        }
    }
}
